<?php

namespace app\admin\controller\wwh;

use app\common\controller\Backend;
use think\Db;

class Template extends Base
{
    /**
     * Template模型对象
     * @var \app\admin\model\wwh\Template
     */
    protected $model = null;
    protected $searchFields = 'id,name,listtpl,showtpl';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wwh\Template;

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 获取模板列表
     */
    public function get_template_list()
    {
        $params = $this->request->only(['keyValue', 'type', 'name'], 'request');

        // 如果有指定keyValue，直接返回
        if (!empty($params['keyValue'])) {
            return ['total' => 1, 'list' => [['name' => $params['keyValue']]]];
        }

        $files = [];
        $this->request->filter(['strip_tags']);

        // 处理自定义模板名称
        if (!empty($params['name'])) {
            $files[] = ['name' => $params['name'] . '.html'];
        }

        // 从数据库获取模板配置
        $template = Db::name('wwh_config')
            ->where('lang', 1)
            ->value('template') ?: 'default';

        $themeDir = ADDON_PATH . 'wwh' . DS . 'view' . DS . $template . DS;

        // 获取目录下所有文件
        if (is_dir($themeDir)) {
            foreach (scandir($themeDir) as $filename) {
                if ($filename === '.' || $filename === '..') {
                    continue;
                }

                // 根据类型过滤文件
                if (!empty($params['type'])) {
                    $rule = $params['type'] === 'column' ? '(column|list)' : $params['type'];
                    if (!preg_match("/^{$rule}(.*)/i", $filename)) {
                        continue;
                    }
                }

                $files[] = ['name' => $filename];
            }
        }

        return [
            'total' => count($files),
            'list' => $files
        ];
    }
}
